package com.youlu.campus.service.course;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.youlu.campus.entity.course.dto.MiliResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : [dengbo]
 * @className : MiliThirdService
 * @description : [米粒三方服务]
 * @createTime : [2022/10/21 14:16]
 */
@Service
@Slf4j
public class MiliThirdService {
    @Autowired
    private RestTemplate restTemplate;

    private final static String MILI_APP_ID = "M10010697";
    private final static String MILI_APP_SECRET = "1edb1ecc3604b881a1200b8091d92ede";
    private final static String MILI_LOGIN_URL = "https://mili-api.milixf.com/api/user/phonelogin";

    public Pair<Boolean, String> getMiliAccessToken(String phone, String openId) {
        Map<String, Object> param = new HashMap<>();
        Long time = System.currentTimeMillis() / 1000;
        Map<String, Object> data = new HashMap<>();
        data.put("phone", phone);
        data.put("openId", openId);
        String dataStr = JSON.toJSONString(data);
        String errorMsg = "米粒登陆异常";
        try {
            String sign = getSign(dataStr, time);
            param.put("sign", sign);
            param.put("data", dataStr);
            param.put("appid", MILI_APP_ID);
            param.put("timestamp", time);
            log.info("param:{}", param);
            ResponseEntity<MiliResult> re = restTemplate.postForEntity(MILI_LOGIN_URL, param, MiliResult.class);
            MiliResult<Map> result = re.getBody();
            log.info("mili login result :{}", result);
            if ("1".equals(result.getErrno())) {
                return Pair.of(true, result.getData().get("token").toString());
            }
            if(StringUtils.isNotBlank(result.getError())){
                errorMsg = result.getError();
            }
        } catch (Exception e) {
            log.error("getMiliAccessToken error", e);
        }
        return Pair.of(false, errorMsg);
    }

    public static String getSign(String data, Long time) throws Exception {
        String str = MILI_APP_ID + data + MILI_APP_SECRET + time;
        return WXPayUtil.MD5(str).toLowerCase();
    }
}
